# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.views import View
from rbac import models


class Auth(View):
	'''登录'''
	def get(self, request):
		return render(request, 'login.html')

	def post(self, request):
		username = request.POST.get('username')
		password = request.POST.get('password')
		user_obj = models.User.objects.filter(username=username, password=password).first()
		if user_obj:
			'''登录成功'''
			permissions = user_obj.roles.filter(permissions__url__isnull=False).values('permissions__url').distinct()
			request.session['is_login'] = '1'
			request.session['usr'] = username
			request.session['permissions'] = list(permissions)
			return redirect('index')
		return render(request, 'login.html', {'error': '用户名或密码错误'})


class Index(View):
	'''首页'''
	def get(self, request):
		return render(request, 'index.html')


class Logout(View):
	'''退出'''
	def get(self, request):
		request.session.flush
		return redirect('login')